#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import re
from pathlib import Path

def convert_absolute_to_relative_paths():
    """
    将Markdown文件中的图片绝对路径转换为相对路径
    """
    # 获取文档根目录
    doc_root = Path('/Users/cangjie_nj/Documents/code/doc').resolve()
    
    # 查找所有 Markdown 文件
    md_files = list(doc_root.rglob('*.md'))
    print(f"找到 {len(md_files)} 个 Markdown 文件")
    
    # 统计信息
    total_converted = 0
    
    # 处理每个 Markdown 文件
    for md_file in md_files:
        try:
            # 读取文件内容
            with open(md_file, 'r', encoding='utf-8') as f:
                content = f.read()
            
            original_content = content
            
            # 查找图片链接 ![alt](path)
            pattern = re.compile(r'!\[([^\]]*)\]\(([^)]+)\)')
            matches = pattern.findall(content)
            
            converted_count = 0
            
            # 处理每个图片链接
            for alt_text, img_path in matches:
                # 检查是否是绝对路径 (以file://开头或者以/开头)
                if img_path.startswith('file://'):
                    # 提取实际路径部分
                    actual_path = img_path[7:]  # 移除 'file://' 前缀
                    
                    # 转换为Path对象
                    abs_path = Path(actual_path).resolve()
                    
                    # 计算相对于当前md文件的相对路径
                    try:
                        relative_path = os.path.relpath(abs_path, md_file.parent)
                        
                        # 替换为相对路径
                        old_link = f'![{alt_text}]({img_path})'
                        new_link = f'![{alt_text}]({relative_path})'
                        content = content.replace(old_link, new_link)
                        print(f"已更新 {md_file.name}: {img_path} -> {relative_path}")
                        converted_count += 1
                        total_converted += 1
                    except ValueError as e:
                        print(f"无法计算相对路径 {md_file} -> {abs_path}: {e}")
                
                elif img_path.startswith('/') and not img_path.startswith('//'):
                    # 处理以/开头的绝对路径
                    abs_path = Path(img_path).resolve()
                    
                    # 计算相对于当前md文件的相对路径
                    try:
                        relative_path = os.path.relpath(abs_path, md_file.parent)
                        
                        # 替换为相对路径
                        old_link = f'![{alt_text}]({img_path})'
                        new_link = f'![{alt_text}]({relative_path})'
                        content = content.replace(old_link, new_link)
                        print(f"已更新 {md_file.name}: {img_path} -> {relative_path}")
                        converted_count += 1
                        total_converted += 1
                    except ValueError as e:
                        print(f"无法计算相对路径 {md_file} -> {abs_path}: {e}")
            
            # 如果内容发生了变化，则写回文件
            if content != original_content:
                with open(md_file, 'w', encoding='utf-8') as f:
                    f.write(content)
                print(f"已保存修改到 {md_file} ({converted_count} 处更改)")
            else:
                print(f"{md_file} 没有需要更改的图片路径")
                
        except Exception as e:
            print(f"处理文件 {md_file} 时出错: {e}")
    
    print(f"\n总共转换了 {total_converted} 处图片路径")

if __name__ == "__main__":
    print("开始将Markdown文件中的图片绝对路径转换为相对路径...")
    convert_absolute_to_relative_paths()
    print("转换完成!")